// pages/order/order.js
const app = getApp();
const api = require('../../utils/api');
const constant = require('../../utils/constant');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //获取全局变量 导航栏的高度statusBarHeight
    statusBarHeight: app.globalData.statusBarHeight,
    // 胶囊
    jiaonang: app.globalData.jiaonang, 
    navigationHeight: app.globalData.navigationHeight,
    BASEURLWWW:constant.BASEURLWWW,
    // tabNav
    tabNav:[
      {id:0,title:"全部"},
      {id:1,title:"待支付"},
      {id:2,title:"待配送"},
      {id:3,title:"待收货"},
      {id:4,title:"已完成"},
      {id:5,title:"已取消"},
    ],
    // 切换前的索引
    oldCurrent:0,
    // tabNav索引
    current: 0, 
    // tab切换和滑动开关
    tabOff: false,
    // 订单数据
    orderListData:[],
    // 是否有数据
    haveData: true,
    // 没有数据提示
    isLastNotice: false,
    // 分页
    pagination:{
      pageNum: 1,  //分页初始值，页号1
      pageSize: 10, //分页初始值，每页20条
      total: null
    },
    // 收货信息弹窗
    freightShow: false,
    // 收货信息
    addressData:{},
    // 数据请求开关，防止无限请求
    requestOff: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    if(options.current){
      this.setData({
        current: options.current
      })
      this.getOrderListData(options.current,this.data.pagination);
    }else{
      this.getOrderListData(0,this.data.pagination);
    }
  },
  // 获取订单列表
  getOrderListData:function(newCurrent,pagiantion){
    let orderListDataArr = this.data.orderListData;
    let trade_status = null;
    let pay_status = null;
    // 全部
    if(newCurrent == 0){
      trade_status = null;
    }
    // 待付款
    if(newCurrent == 1){
      trade_status = 0;
      pay_status = 0;
    }
    // 待配送
    if(newCurrent == 2){
      trade_status = 0;
      pay_status = 1;
    }
    // 待收货
    if(newCurrent == 3){
      trade_status = 1;
    }
    // 已完成
    if(newCurrent == 4){
      trade_status = 2;
    }
    // 已取消
    if(newCurrent == 5){
      trade_status = 3;
    }
    // 判断数据是不是已经是全部
    if(orderListDataArr.length == this.data.pagination.total){
      this.setData({
        isLastNotice: true,
      })
    }else{
      // 开始请求
      wx.showLoading();
      this.setData({
        requestOff:false
      })
     if(pay_status == 0 && trade_status == 0){ // 待支付
        api.getOrderListIsOrNotPay(trade_status,pay_status,pagiantion).then(res => {
          this.getOrderListResult(res,orderListDataArr,newCurrent);
        })
      }else if(pay_status == 1 && trade_status == 0){ // 待配送
        api.getOrderListIsOrNotPay(trade_status,pay_status,pagiantion).then(res => {
          this.getOrderListResult(res,orderListDataArr,newCurrent);
        })
      }else{ // 其他
        api.getOrderList(trade_status,pagiantion).then(res => {
          this.getOrderListResult(res,orderListDataArr,newCurrent);
        })
      }
    }
  },
  // 订单查询结果处理
  getOrderListResult: function(res,orderListDataArr,newCurrent){
     // 获取到的列表数据不为空
     if(res.code == 0){
      if(res.data.data.total != 0){
        res.data.data.list.forEach(item => {
          if(item.trade_status == 0 && item.pay_status == 0){
            item.statusStr = '待付款'
          }
          if(item.trade_status == 0 && item.pay_status == 1){
            item.statusStr = '待配送'
          }
          if(item.trade_status == 1 && item.pay_status == 1){
            item.statusStr = '待收货'
          }
          if(item.trade_status == 2){
            item.statusStr = '已完成'
          }
          if(item.trade_status == 3){
            item.statusStr = '已取消'
          }
          if(item.trade_status == 4){
            item.statusStr = '待退货'
          }
          if(item.trade_status == 5){
            item.statusStr = '已退货'
          }
          orderListDataArr.push(item);
        })
        this.setData({
          current: newCurrent,
          haveData: true,
          orderListData: orderListDataArr,
          'pagination.total':  res.data.data.total,
          isLastNotice: false,
          requestOff: true
        })
      }else{
        this.setData({
          current: newCurrent,
          haveData: false,
          orderListData: [],
          'pagination.total': null,
          requestOff: true
        })
      }
     }else{
      wx.showToast({
        title: res.msg,
        icon: 'none',
        duration: 1500
      })
      this.setData({
        current: newCurrent,
        haveData: false,
        requestOff: true
      })
    }
    wx.hideLoading();
     
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 返回上一级
  back:function(){
    wx.reLaunch({
      url: '/pages/personal/personal'
    })
  },
  onReachBottom:function(){
    
  },
  // 选项卡切换
  tabSwitch:function(e){
    if(this.data.requestOff){
      let oldCurrent = this.data.current;
      this.setData({
        oldCurrent,
        tabOff: true,
        current: e.currentTarget.dataset.id
      })
    }
  },
  // 选项卡滑动
  tabChange:function(e){
    if(this.data.requestOff){
      if(this.data.tabOff){ 
        let current = this.data.current;
        // 选项卡点击后，新旧索引已经存放，直接使用新的索引
        this.setData({
          current,
          'pagination.total': null,
          'pagination.pageNum': 1,
          orderListData: [],
          tabOff: false
        })
      }else{
        // 选项卡没有点击，对新旧索引进行保存
        let oldCurrent = this.data.current;
        this.setData({
          oldCurrent,
          current: e.detail.current,
          'pagination.total': null,
          'pagination.pageNum': 1,
          orderListData: [],
          tabOff: false
        })
      }
      this.getOrderListData(this.data.current,this.data.pagination);
    }
    
  },
  // 上拉加载
  bindscrolltolower:function(){
    let pagination = {
      pageNum: this.data.pagination.pageNum + 1,
      pageSize: this.data.pagination.pageSize
    }
    this.setData({
      'pagination.pageNum': pagination.pageNum
    })
    this.getOrderListData(this.data.current,pagination);
  },
  // 背景不滚动
  dontMove: function(){
    return;
  },
  // 跳转到商品详情
  jumpToGoodsDetail:function(e){
    let goodsId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/goods/goods?goods_id='+goodsId
    })
  },
  // 查看收货信息
  aboutAdress:function(e){
    this.setData({
      freightShow: true,
      addressData: e.currentTarget.dataset.item
    })
  },
  // 关闭运费弹窗
  closeFreighDailog: function(){
    this.setData({
      freightShow: false
    })
  },
  // 立即付款
  newPay:function(e){
    let that = this;
    let order_no = e.currentTarget.dataset.item.order_no;
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if(res.code && res.code != ''){
          api.getPayOptions(res.code,order_no).then(res => {
            if(res.code == 0){
              wx.requestPayment(
                {
                'timeStamp': res.data.data.timeStamp,
                'nonceStr': res.data.data.nonceStr,
                'package': res.data.data.package,
                'signType': res.data.data.signType,
                'paySign': res.data.data.paySign,
                'success':function(res){
                  wx.showToast({
                    title: '支付成功',
                    icon: 'success'
                  })
                  that.setData({
                    'pagination.total': null,
                    'pagination.pageNum': 1,
                    'pagination.pageSize': 10,
                    orderListData: [],
                    tabOff: false
                  })
                  that.getOrderListData(2,that.data.pagination);
                },
                'fail':function(res){
                  wx.showToast({
                    title: res.msg,
                    icon: 'error'
                  })
                },
                'complete':function(res){
                }
                })
            }
          })
        }
      },
      fail:res => {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    })
  },
  // 重新购买
  againBuy:function(e){
    let order = e.currentTarget.dataset.item;
    let cartGoods = [];
    let goodsIdArr = [];
    order.order_goods.forEach(item => {
      let goodsObj = {
        goods_id: item.goods_id,
        goods_spec_id: item.goods_spec_id,
        key_name: item.key_name,
        key_value: item.key_value,
        price:item.shop_price,
        goods_num: item.qty,
      };
      cartGoods.push(goodsObj);
      goodsIdArr.push(item.goods_id)
    })
    api.addToCart(cartGoods).then(res => {
      if(res.code == 0){
        wx.reLaunch({
          url: `/pages/car/car?goods_id=${JSON.stringify(goodsIdArr)}`,
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 1500
        })
      }
    })
  },
  // 取消订单
  cancelOreder:function(e){
    let order_no = e.currentTarget.dataset.item.order_no;
    let current = this.data.current;
    let pagination = {
      pageNum: 1,
      pageSize: 10
    }
    api.cancelOrder(order_no).then(res => {
      if(res.code == 0){
        this.setData({
          orderListData: [],
        })
        this.getOrderListData(current,pagination);
      }
    })
  },
  // 删除订单
  deleteOrder:function(e){
    let order_id = e.currentTarget.dataset.item.order_id;
    let current = this.data.current;
    let pagination = {
      pageNum: 1,
      pageSize: 10
    }
    api.deleteOrder([order_id]).then(res => {
      if(res.code == 0){
        this.setData({
          orderListData: [],
        })
        this.getOrderListData(current,pagination);
      }
    })
  },
  // 确认收货
  confirmOrder:function(e){
    let order_id = e.currentTarget.dataset.item.order_id;
    let current = this.data.current;
    let pagination = {
      pageNum: 1,
      pageSize: 10
    }
    api.confirmOrder(order_id).then(res => {
      if(res.code == 0){
        this.setData({
          orderListData: [],
        })
        this.getOrderListData(current,pagination);
      }
    })
  },
  // 申请退货
  applyRefunds:function(e){
    let order_no = e.currentTarget.dataset.order_no;
    wx.navigateTo({
      url: `/pages/afterSales/afterSales?order_no=${order_no}`,
    })
  },
  // 查看售后
  jumpToAfterSales:function(){
    wx.reLaunch({
      url: '/pages/afterSales/afterSales?current=2'
    })
  },
  // 跳转到评价
  jumpToMyEvaluate:function(e){
    let item = e.currentTarget.dataset.item;
    let orderData = {
      
    }
    console.log(item);
    // wx.reLaunch({
    //   url: '/pages/myEvaluate/myEvaluate'
    // })
  }
})